package com.yunshipei.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.yunshipei.base.EnterBaseSubscriber;
import com.yunshipei.common.Globals;
import com.yunshipei.common.net.HttpMethods;
import com.yunshipei.core.manager.XCloudSDKManager;
import com.yunshipei.core.utils.SystemUtils;
import com.yunshipei.db.DatabaseUtil;
import com.yunshipei.enterplorer.R;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.model.MainExtraBean;
import com.yunshipei.model.UserInfo;
import com.yunshipei.model.YspEvent;
import com.yunshipei.ui.activity.MainActivity;
import com.yunshipei.ui.activity.MessageActivity;
import com.yunshipei.ui.activity.NoContactsSettingsActivity;
import com.yunshipei.utils.ToastUtils;

import org.json.JSONObject;

import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import io.rong.app.RongCloudEvent;
import io.rong.app.utils.StringUtilSub;
import io.rong.eventbus.EventBus;
import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.model.Event;
import io.rong.imlib.RongIMClient;

public class NoContactsNavigationFragment extends BaseNavFragment implements MenuFragment.OnFragmentInteractionListener {

    private static final String ARGS_IS_CACHE_DATA = "com.enterplorer.is.cache.data";
    private static final String ARGS_NAVIGATION_DATA = "com.enterplorer.navigation.data";


    private MainExtraBean mMainExtraBean;
    private boolean isFromCache = false;

    private Fragment[] mFragments = new Fragment[2];

    private Context mContext;
    private Disposable mDisposable;

    public static NoContactsNavigationFragment newInstance(MainExtraBean mainExtraBean, boolean fromCache) {
        NoContactsNavigationFragment noContactsNavigationFragment = new NoContactsNavigationFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(ARGS_NAVIGATION_DATA, mainExtraBean);
        bundle.putSerializable(ARGS_IS_CACHE_DATA, fromCache);
        noContactsNavigationFragment.setArguments(bundle);
        return noContactsNavigationFragment;
    }

    public static NoContactsNavigationFragment newInstance(MainExtraBean mainExtraBean) {
        NoContactsNavigationFragment noContactsNavigationFragment = new NoContactsNavigationFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(ARGS_NAVIGATION_DATA, mainExtraBean);
        noContactsNavigationFragment.setArguments(bundle);
        return noContactsNavigationFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        isFromCache = getArguments().getBoolean(ARGS_IS_CACHE_DATA);
        mMainExtraBean = (MainExtraBean) getArguments().getSerializable(ARGS_NAVIGATION_DATA);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_no_contacts, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        boolean h5 = h5Client();
        if (savedInstanceState != null) {
            mFragments[0] = getChildFragmentManager().findFragmentByTag(h5 ? H5HomeFragment.class.getName() : HomeFragment.class.getName());
            mFragments[1] = getChildFragmentManager().findFragmentByTag(MenuFragment.class.getName());
        } else {
            String userName = mMainExtraBean.getUserInfo().getName();
            String userImage = mMainExtraBean.getUserInfo().getAvatar();
            mFragments[0] = h5 ? H5HomeFragment.newInstance(mMainExtraBean) : HomeFragment.newInstance(mMainExtraBean);
            mFragments[1] = MenuFragment.newInstance(userName, userImage);
            getChildFragmentManager().beginTransaction().add(R.id.fl_home_fragment, mFragments[0], mFragments[0].getClass().getName()).commit();
            getChildFragmentManager().beginTransaction().add(R.id.fl_home_menu, mFragments[1], mFragments[1].getClass().getName()).commit();
        }
    }

    @SuppressLint("CommitPrefEdits")
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!isFromCache) {
            resetIM();
        }
    }

    private boolean flag = false;

    @Override
    public void onResume() {
        super.onResume();
        if (!flag) {
            flag = true;
            MenuFragment menuFragment = ((MenuFragment) mFragments[1]);
            menuFragment.setOpenPCBtnEnable(false);
            menuFragment.setBackBtnEnable(false);
            menuFragment.setForwardBtnEnable(false);
            menuFragment.setHomeBtnEnable(false);
            menuFragment.setFontSizeBtnEnable(false);
            menuFragment.setShareBtnEnable(false);
        }
    }

    private int tokenIncorrectCount = 0;
    private boolean prepareFinish = false;

    private void connectIM(String token, final String uuid) {
        RongIM.connect(token, new RongIMClient.ConnectCallback() {

            @Override
            public void onTokenIncorrect() {
                if (tokenIncorrectCount < 3) {
                    //刷新Token
                    HttpMethods.getInstance().reFetchToken(uuid, new EnterBaseSubscriber() {
                        @Override
                        public void onSuccess(JSONObject data) {
                            String newToken = data.optString("token");
                            if (!TextUtils.isEmpty(newToken)) {
                                YspPreferences.getInstance().getSharedPreferences().edit().putString(Globals.YSP_TOKEN, newToken).apply();
                                connectIM(newToken, uuid);
                            } else {
                                onFailure("token为空");
                            }
                        }

                        @Override
                        public void onFailure(String errorMessage) {
                        }
                    });
                    tokenIncorrectCount++;
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode arg0) {
                prepareFinish = true;
            }

            @SuppressLint("CommitPrefEdits")
            @Override
            public void onSuccess(String arg0) {
                YspPreferences.getInstance().getSharedPreferences().edit().putBoolean("RCSconnectStatus", true).apply();
                RongCloudEvent.getInstance().setOtherListener();
                EventBus.getDefault().post(new YspEvent.ConnectEvent());
                RongContext.getInstance().getEventBus().post(Event.ConnectEvent.obtain(true));
                prepareFinish = true;
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }

    @Override
    public String captureHomeWebView() {
        DrawerLayout drawerLayout = ((MainActivity) mContext).getDrawer();
        boolean viewShowing = !isHidden() && !mFragments[0].isHidden() && drawerLayout != null && !drawerLayout.isDrawerOpen(Gravity.LEFT);
        return mMainExtraBean.getManagerCode() >= 2 ? ((H5HomeFragment) mFragments[0]).getHomeWebViewCaptureURL(viewShowing) : ((HomeFragment) mFragments[0]).getHomeWebViewCaptureURL(viewShowing);
    }

    @SuppressLint("CommitPrefEdits")
    @Override
    public void resetIM() {
        final UserInfo userInfo = mMainExtraBean.getUserInfo();
        final String uuid = userInfo.getUuid();
        String userName = userInfo.getName();
        String userAvatar = userInfo.getAvatar();
        String companyId = userInfo.getCompanyId();
        String password = userInfo.getPassword();
        RongContext.getInstance().setCurrentUserInfo(new io.rong.imlib.model.UserInfo(uuid, userName, TextUtils.isEmpty(userAvatar) ? null : Uri.parse(userAvatar)));
        final DatabaseUtil databaseUtil = new DatabaseUtil();
        final HttpMethods httpMethods = HttpMethods.getInstance();
        YspPreferences.getInstance().getSharedPreferences().edit().putString(Globals.YSP_USER_INFO, StringUtilSub.base64(userInfo)).apply(); //IM相关某些页面需要使用
        mDisposable = httpMethods.allContacts(companyId, uuid, password).map(new Function<List<UserInfo>, Boolean>() {
            @Override
            public Boolean apply(List<UserInfo> userInfos) throws Exception {
                databaseUtil.InsertAllUser(userInfos);
                return true;
            }
        }).subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean b) throws Exception {
                connectIM(mMainExtraBean.getToken(), uuid);
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                ToastUtils.showToast(XCloudSDKManager.getInstance().generateError(throwable));
                connectIM(mMainExtraBean.getToken(), uuid);
            }
        });
    }

    @Override
    public void goFroward() {

    }

    @Override
    public void goBack() {

    }

    @Override
    public void refresh() {
        ((HomeFragment) mFragments[0]).refresh();
    }

    @Override
    public void home() {

    }

    @Override
    public void message() {
        if (prepareFinish) {
            startActivity(new Intent(mContext, MessageActivity.class));
        } else {
            ToastUtils.showToast("正在初始化消息，请稍候再试...");
        }
    }

    @Override
    public void openPC() {

    }

    @Override
    public void settings() {
        startActivity(new NoContactsSettingsActivity.NoContactsSettingIntentBuilder(mContext).setMainExtra(mMainExtraBean).getIntent());
    }

    @Override
    public void share(View view) {

    }

    @Override
    public void onMoreMenuHide(boolean hide) {

    }

    @Override
    public void showFontSizeSetting() {

    }

    private boolean h5Client() {
        if (SystemUtils.isPad(mContext)) {
            return true;
        }
        int managerCode = mMainExtraBean.getManagerCode();
        return managerCode >= 2;
    }
}
